import { NTree } from "naive-ui";
import type { TreeProps, TreeInst } from "naive-ui";

import type { BaseComponentType, OmitHTMLAttributes } from "../types";
import { getSlotsDom } from "../utils";
import { type VirtualListScrollToOptions } from "vueuc";

export class TreeFactory {
  private attrs: OmitHTMLAttributes<
    | "draggable"
    | "onDragend"
    | "onDragenter"
    | "onDragleave"
    | "onDragover"
    | "onDragstart"
    | "onDrop"
    | "onLoad"
  > = {};
  private props: TreeProps = {};
  private emptySlot: BaseComponentType = null;
  private domRef: TreeInst | null = null;

  setAttrs(attrs: OmitHTMLAttributes<"draggable">) {
    this.attrs = attrs;
    return this;
  }
  setProps(props: TreeProps) {
    this.props = props;
    return this;
  }
  setEmpty(component: BaseComponentType) {
    this.emptySlot = component;
    return this;
  }
  scrollTo(options: VirtualListScrollToOptions | number, y?: number) {
    if (typeof options === "number") {
      this.domRef?.scrollTo(options, y || 0);
    } else {
      this.domRef?.scrollTo(options);
    }
  }

  getCheckedData() {
    return this.domRef?.getCheckedData();
  }
  getIndeterminateData() {
    return this.domRef?.getIndeterminateData();
  }

  create() {
    return (
      <NTree
        ref={(el: HTMLElement) => {
          this.domRef = el as unknown as TreeInst;
        }}
        {...this.props}
        {...this.attrs}
      >
        {{
          empty:
            this.emptySlot != null
              ? () => getSlotsDom(this.emptySlot as BaseComponentType)
              : null,
        }}
      </NTree>
    );
  }
}
